package org.melanesia.beans;

import java.lang.reflect.Field;
import java.util.Map;

import org.melanesia.beans.exceptions.PropertySetException;


class FieldSetter implements Setter {

    private Field field;

    FieldSetter(Field field) {
        this.field = field;
    }
    
    @Override
    public void set(Object bean, Object value, Map<String, Class<?>> intermediateBeanClasses) {
        boolean accessible = field.isAccessible();
        
        try {
            if (!accessible) {
                BeanUtils.setAccessible(field, true);
            }
            
            Object acceptedValue = BeanUtils.cast(value, getAcceptedType());
            field.set(bean, acceptedValue);
            
        } catch (Throwable t) {
            throw new PropertySetException("Error mapping bean \"" + bean.getClass() + "\". Cannot set value of field \"" + field.getName() + "\" of class \"" + getAcceptedType() + "\" to \"" + value + "\" of class \"" + (value == null ? "unknown" : value.getClass()) + "\".", t);
        } finally {
            BeanUtils.setAccessible(field, accessible);
        }
    }

    @Override
    public Class<?> getAcceptedType() {
        return field.getType();
    }
}
